using StackExchange.Redis;
using Microsoft.Extensions.Configuration;
using System;

namespace RabbitTraceability.API.Application.Utils
{
    /// <summary>
    /// Redis操作帮助类，包含服务配置、连接字符串和健康检查
    /// </summary>
    public static class RedisHelper
    {
        private static Lazy<ConnectionMultiplexer>? _lazyConnection;
        private static string? _connectionString;

        /// <summary>
        /// 初始化Redis连接（需在程序启动时调用一次）
        /// </summary>
        /// <param name="configuration">应用配置</param>
        public static void Init(IConfiguration configuration)
        {
            // 从配置中读取各个字段
            var host = configuration["Redis:Host"];
            var port = configuration["Redis:Port"];
            var password = configuration["Redis:Password"];
            var database = configuration["Redis:Database"];
            var connectTimeout = configuration["Redis:ConnectTimeout"];
            var responseTimeout = configuration["Redis:ResponseTimeout"];

            // 拼接连接字符串
            _connectionString = $"{host}:{port},password={password},defaultDatabase={database},connectTimeout={connectTimeout},responseTimeout={responseTimeout}";

            if (string.IsNullOrWhiteSpace(_connectionString) || string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(port))
                throw new ArgumentException("Redis连接字符串不能为空，请检查配置文件！");

            _lazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionString));
        }

        /// <summary>
        /// 获取Redis数据库实例
        /// </summary>
        public static IDatabase GetDatabase()
        {
            if (_lazyConnection == null)
                throw new InvalidOperationException("RedisHelper未初始化，请先调用Init方法。");
            return _lazyConnection.Value.GetDatabase();
        }

        /// <summary>
        /// 获取Redis连接字符串
        /// </summary>
        public static string? GetConnectionString() => _connectionString;

        /// <summary>
        /// 检查Redis服务健康状态
        /// </summary>
        /// <returns>true表示健康，false表示不可用</returns>
        public static bool CheckHealth()
        {
            try
            {
                var db = GetDatabase();
                return db.Ping().TotalMilliseconds < 1000; // 1秒内响应视为健康
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 根据key获取Redis中的值
        /// </summary>
        /// <param name="key">Redis键</param>
        /// <returns>对应的值，如果不存在则返回null</returns>
        public static string? GetValue(string key)
        {
            var db = GetDatabase();
            return db.StringGet(key);
        }
    }
} 